const request = require("../../utils/request.js");

Page({
  data: {
    loading: true,
    isError: false
  },

  onLoad() {
    this.setData({ loading: true })
    wx.removeStorageSync('userInfo');
    // this.login();
    const versionInfo = wx.getAccountInfoSync();
    const { envVersion = __wxConfig } = versionInfo.miniProgram;
    if (envVersion === 'release' || envVersion === 'trial') {
      this.login();
    } else {
      const token = wx.getStorageSync('token');
      if (token) {
        this.verifyToken();
      } else {
        this.login();
      }
    }
  },

  login() {
    const that = this;
    wx.login({
      success: (res) => {
        if (res.errMsg == 'login:ok') {
          const jsCode = res.code;
          request("login", { "jsCode": jsCode }, "POST")
            .then(res => {
              if (res.code == '500') {
                this.setData({ isError: true })
                console.log('error: ', res.msg);
              } else if (res.code = '200') {
                if (res.data.openid && res.data.token) {
                  wx.setStorageSync('token', res.data.token);
                }
              } else {
                this.setData({ isError: true })
              }
              that.intoSystem();
            })
            .catch(err => {
              console.log('login error ', err)
              that.setData({ isError: true })
              that.intoSystem();
            })
        }
      },
    })
  },
  verifyToken() {
    const that = this;
    request('verify-token', {}, 'POST').then(res => {
      // setTimeout(() => {
      //   console.log('verify token result: ', res)
      // }, 2000);
      that.intoSystem();
    })
      .catch(err => {
        console.log('verify token error ', err)
        that.setData({ isError: true })
        that.intoSystem();
      })
  },

  async intoSystem() {
    // TODO
    await this.waitOneSeconds();
    this.setData({ loading: false })
    wx.switchTab({
      url: '/pages/home/home',
      // url: '/pages/usercenter/index',
    })
  },

  waitOneSeconds() {
    return new Promise(resolve => setTimeout(resolve, 1000));
  },

  restartSystem() {
    console.log('restartSystem...')
    wx.restartMiniProgram({ path: '/pages/load/index' })
  },
})